#coding:utf-8

import urllib
import subprocess
import sys
import socket


def getPort(url):
    pass
    parts = url.split(':')
    return parts[0], int(parts[-1])


def monitor_process(key_word):
    p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['grep', key_word], stdin=p1.stdout, stdout=subprocess.PIPE)
    p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
    lines = p3.stdout.readlines()
    lines = list(lines)
    # print(list(lines))
    # print(len(lines))

    if len(lines) == 0:
        return None

    line = lines[0]
    try:
        line = bytes.decode(line)
    except:
        pass
    line = line.split()

    return int(line[1])

    #sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd))
    #subprocess.call(cmd, shell=True)


# def agent_():
#     p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
#     p2 = subprocess.Popen(['grep', "MainRun"], stdin=p1.stdout, stdout=subprocess.PIPE)
#     p3 = subprocess.Popen(['grep', '-v', 'grep'], stdin=p2.stdout, stdout=subprocess.PIPE)
#     lines = p3.stdout.readlines()
#     lines = list(lines)
#     # print(list(lines))
#     # print(len(lines))
#
#     if len(lines) == 0:
#         return 0
#
#     return len(lines)

def monitor_port(protocol, port):
    address = ('127.0.0.1', port)
    socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM
    client = socket.socket(socket.AF_INET, socket_type)
    try:
        client.bind(address)
    except Exception as  e:
        return False
    else:
        #sys.stderr.write('port[%s-%s] is lost, run [%s]\n' % (protocol, port, cmd))
        #subprocess.call(cmd, shell=True)
        pass
    finally:
        client.close()

    return True
